from Data import search_file
import win32com.client
from datetime import datetime
import os

chinese_path = None


def hardware_manual_en(version_type, is_folder):
    # 先选择要处理的英文文件
    if is_folder:
        filepaths = search_file.select_folder("选择文件夹")
    else:
        filepaths = search_file.select_file()
    if filepaths == "-1":
        return "-1"

    # 如果是中文手册版本，再选择中文手册文件夹
    global chinese_path
    if version_type == "中文手册版本":
        chinese_path = search_file.select_folder("选择中文手册")
        if chinese_path == "-1":
            return "-1"
        # 不需要额外处理路径
        chinese_path = os.path.normpath(chinese_path)

    for filepath in filepaths:
        if "~" in filepath:
            continue
        # 统一路径分隔符并获取文件名
        filepath = os.path.normpath(filepath)  # 规范化路径
        filename = os.path.basename(filepath)  # 获取文件名

        # 检查文件后缀
        if not filename.lower().endswith(('.doc', '.docx')):
            continue

        try:
            print(f"正在处理：{filename}")
            word = win32com.client.DispatchEx("Word.Application")
            word.Visible = True
            word.DisplayAlerts = False

            # 使用完整路径打开文档
            try:
                doc = word.Documents.Open(os.path.abspath(filepath))
            except Exception as e:
                print(f"无法打开文件，请确保文件路径正确且未被占用: {str(e)}")
                word.Quit()
                del word
                continue

            version = cover_version(doc)
            version_revision = revision_record(filename)
            # if version_revision == "-1":
            #     continue
            version_refresh = refresh_cover(version, version_type, doc, version_revision)

            doc.Save()
            # 确保正确关闭 Word
            doc.Close(SaveChanges=False)
            word.Quit()
            del word
            rename(version_refresh, filepath, filename)
        except Exception as e:
            print(f"处理文件 {filename} 时出错: {str(e)}")
            try:
                doc.Close(SaveChanges=False)
                word.Quit()
                del word
            except:
                pass
            continue
    print("程序执行完成！！！")


def rename(version, filepath, filename):
    if version == "-1":
        return "-1"
    try:
        dirname = os.path.dirname(filepath)
        if "(" in filename and ")" in filename:
            # 处理已有版本号的文件名
            base_name = filename[:filename.rfind('(')]
            # 检查并修正"交换机"和"硬件安装手册"之间的空格
            # if "交换机硬件安装手册" in base_name:
            #     base_name = base_name.replace("交换机硬件安装手册", "交换机 硬件安装手册")
            new_filename = f"{base_name}({version}).docx"
        else:
            # 处理新文件名
            base_name = filename.split(".doc")[0]
            # if base_name.endswith("交换机"):
            #     base_name = base_name + " "
            new_filename = f'{base_name} ({version}).docx'
        new_path = os.path.join(dirname, new_filename)

        # 如果新旧文件名相同，直接跳过
        if os.path.basename(filepath) == new_filename:
            return

        # 检查目标路径是否已存在同名文件
        if os.path.exists(new_path):
            return

        os.rename(filepath, new_path)

    except Exception as e:
        print(f"重命名失败: {str(e)}")


# 获取修订记录版本
def get_word_version(doc):
    try:
        version = doc.Application.Version
        return float(version)
    except:
        return 15.0  # 默认按 Word 2013 处理


def revision_record(filename):
    # 只在中文手册版本时执行
    if not chinese_path:
        return "-1"

    flag = False
    english_model = filename.split(" ")[1]
    # print(english_model)
    try:
        for file in os.listdir(str(chinese_path)):
            if file.lower().endswith(('.doc', '.docx')):
                if "系列" in file:
                    chinese_model = file.split("系列")[0]
                    if english_model == chinese_model:
                        version = file.split("(")[1].split(")")[0]
                        # print(chinese_model)
                        flag = True
                        return version
                else:
                    chinese_model = file.split("交换机")[0]
                    if english_model == chinese_model:
                        version = file.split("(")[1].split(")")[0]
                        # print(chinese_model)
                        flag = True
                        return version
    except Exception as e:
        print(f"读取文件夹失败: {str(e)}")
        return "-1"

    if not flag:
        print(f"{english_model} 未找到中文手册")
        flag = False
        return "-1"


def cover_version(doc):
    word_version = get_word_version(doc)
    version_text = None
    date_text = None
    version = None
    data = None
    version_index = 0
    data_index = 0

    if word_version < 16.0:  # Word 2013
        for i in range(min(50, doc.Paragraphs.Count)):
            try:
                text = doc.Paragraphs(i + 1).Range.Text.strip()
                if text:
                    if "Document version:" in text and not version_text:
                        version_text = text
                        version_index = i + 1
                    elif "Date:" in text and not date_text:
                        date_text = text
                        data_index = i + 1
            except:
                continue
    else:  # Word 2016
        for i in range(min(50, doc.Paragraphs.Count)):
            try:
                text = doc.Paragraphs[i].Range.Text.strip()
                if text:
                    if "Document version:" in text and not version_text:
                        version_text = text
                        version_index = i
                    elif "Date:" in text and not date_text:
                        date_text = text
                        data_index = i
            except:
                continue

    if not version_text:
        print("未找到Document version")
    else:
        version = version_text.split(': ')[1].strip()
    if not date_text:
        print("未找到Date")
    else:
        data = date_text.split(': ')[1].strip()

    return version, data, version_index, data_index


def switch_date(date):
    parts = date.split(' ')
    month_date = parts[0]
    day = parts[1].rstrip(',')  # 移除日期中的逗号
    year = parts[2]

    # 处理日期，移除前导零
    if day.startswith('0'):
        day = day[1:]

    month_map = {
        "01": "January",
        "02": "February",
        "03": "March",
        "04": "April",
        "05": "May",
        "06": "June",
        "07": "July",
        "08": "August",
        "09": "September",
        "10": "October",
        "11": "November",
        "12": "December"
    }

    if month_date in month_map:
        month = month_map[month_date]
        return f"{month} {day}, {year}"
    return date


def refresh_cover(value, version_type, doc, version_revision):
    word_version = get_word_version(doc)
    version = None
    if value[0] and value[1]:
        version = value[0]
        data = value[1]
        version_index = value[2]
        data_index = value[3]

        if version_type == "封面版本":
            data = datetime.now().strftime('%m %d, %Y')
            data = switch_date(data)
        if version_type == "封面版本+1":
            version = f'V{float(version.split("V")[1]) + 0.1}'
            data = datetime.now().strftime('%m %d, %Y')
            data = switch_date(data)
        if version_type == "中文手册版本":
            if version_revision == "-1" or version_revision == "-1":
                return "-1"
            else:
                data = datetime.now().strftime('%m %d, %Y')
                data = switch_date(data)
                version = version_revision

        if word_version < 16.0:  # Word 2013
            # 设置文档版本
            version_para = doc.Paragraphs(version_index)
            version_current_range = version_para.Range
            version_current_range.Text = f'Document version: {version}\n'
            # version_current_range.Style = "封面文档版本"

            # 设置归档日期
            data_para = doc.Paragraphs(data_index)
            data_current_range = data_para.Range
            data_current_range.Text = f'Date: {data}\n'
            # data_current_range.Style = "封面文档版本"
        else:  # Word 2016
            # 设置文档版本
            version_para = doc.Paragraphs[version_index]
            version_current_range = version_para.Range
            version_current_range.Text = f'Document version: {version}\n'
            # version_current_range.Style = "封面文档版本"

            # 设置归档日期
            data_para = doc.Paragraphs[data_index]
            data_current_range = data_para.Range
            data_current_range.Text = f'Date: {data}\n'
            # data_current_range.Style = "封面文档版本"

        # 统一设置缩进
        # doc.Application.Selection.HomeKey(Unit=6)  # 移动到文档开头
        # doc.Application.Selection.Find.Execute("Document version:")
        # doc.Application.Selection.Paragraphs.LeftIndent = 88
        #
        # doc.Application.Selection.HomeKey(Unit=6)  # 移动到文档开头
        # doc.Application.Selection.Find.Execute("Date:")
        # doc.Application.Selection.Paragraphs.LeftIndent = 88
    return version


if __name__ == '__main__':
    # hardware_manual("封面版本", True)
    hardware_manual_en("中文手册版本", True)
